
const Service = require('egg').Service;
const qs = require('querystring');
const https = require('https');

class BaiduService extends Service {

    async baiduOcr(data) {
        const ctx = this.ctx;
        return new Promise(async (resolve, reject) => {
            try {
                const accessToken = await this.getAccessToken();
                const param = qs.stringify({
                    'access_token': accessToken,
                });
                const result = await ctx.curl(`https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?${param}`, {
                    timeout: 5000,
                    method: 'POST',
                    contentType: "application/x-www-form-urlencoded",
                    data: data
                });
                if (result.data && result.data.error_msg) {
                    reject(new Error(result.data.error_msg))
                } else {
                    resolve(result.data)
                }
            } catch (error) {
                reject(new Error(error))
            }
        })
    }

    async getAccessToken() {
        const ctx = this.ctx;
        const { appId, apiKey, secretKey } = ctx.app.config.baidu
        return new Promise(async (resolve, reject) => {
            const access_token = await ctx.app.redis.get('baidu_access_token') // 获取redis
            if (access_token) {
                resolve(access_token)
                return
            }

            const param = qs.stringify({
                'grant_type': 'client_credentials',
                'client_id': apiKey,
                'client_secret': secretKey
            });

            const result = await ctx.curl(`https://aip.baidubce.com/oauth/2.0/token?${param}`, {
                dataType: 'json',
                timeout: 5000,
                method: 'POST',
                contentType: "application/json",
                data: JSON.stringify({})
            });
            if (result.data && result.data.error) {
                reject(new Error(result.data.error_description))
            }

            await this.app.redis.set('baidu_access_token', result.data.access_token, 'EX', result.data.expires_in)
            resolve(result.data.access_token)
        })
    }
}

module.exports = BaiduService;
